import axios from 'axios'
import qs from 'qs'

// 基础配置
let baseURL
if (process.env.NODE_ENV === 'production') {
  baseURL = process.env.VUE_APP_API_PRODUCTION
} else if (process.env.NODE_ENV === 'test') {
  baseURL = process.env.VUE_APP_API_TEST
} else {
  baseURL = process.env.VUE_APP_API_DEVELOPMENT
}

axios.defaults.baseURL = baseURL
axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.timeout = process.env.VUE_APP_API_TIMEOUT

let cancel
const promiseArr = {}
const CancelToken = axios.CancelToken
// Add a request interceptor
axios.interceptors.request.use(
  function(config) {
    // todo: 全局 loading
    // 发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
      promiseArr[config.url]()
      promiseArr[config.url] = cancel
    } else {
      promiseArr[config.url] = cancel
    }
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
axios.interceptors.response.use(
  function(response) {
    return response
  },
  function(error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)

function checkStatus(response) {
  return response
}

function checkCode(res) {
  // 这里可以做通用错误请求提示
  return res
}

const request = {
  baseURL,
  post(url, data) {
    return axios({
      method: 'post',
      url,
      data: qs.stringify(data),
    }).then(response => Promise.resolve(response.data))
  },
  postForm(url, data) {
    return axios({
      method: 'post',
      url,
      data,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    }).then(response => Promise.resolve(response.data))
  },
  get(url, params) {
    return axios({
      method: 'get',
      url,
      params,
      cancelToken: new CancelToken(c => {
        cancel = c
      }),
    }).then(response => Promise.resolve(response.data))
  },
}
export default request
